import 'package:fig/models/media_category.dart';
import 'package:fig/sqlite/sql_manager.dart';
import 'package:fig/utils/config.dart';
import 'package:sqflite/sqflite.dart';

// 电影分类表
class TableMediaCategory extends TableBase {
  // 表名
  static final String tableName = 'media_category';

  static final String columnOriginId = "origin_id"; // 第三方的ID
  static final String columnTitle = "title";

  TableMediaCategory(); // 匿名构造函数

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnOriginId integer NOT NULL UNIQUE,
    $columnTitle text,
    ${TableBase.columnCreateTime} integer
    )''');
  }

  Future<int> insert(MediaCategory category) async {
    Database db = await SqlManager.getCurrentDatabase();
    int insertedId = Sqflite.firstIntValue(await db.query(tableName, where: '$columnOriginId=?', whereArgs: [category.originId]));
    // print('当前要插入的分类[${category.title}]主键ID:$insertedId');

    int recordId = 0;
    if (insertedId == null || insertedId == 0) {
      // 诡异的 dart 语法，firstIntValue的返回值居然可以为null
      recordId = await db.insert(tableName, category.toMap()).catchError((error) {
        print('insert category error: $error');
      });
    }

    // print('要插入的数据为 ${category.toMap()} 插入后的 recordId $recordId');
    return recordId;
  }

  // 插入关联关系
  Future<void> insertMap(int mediaId, int originCategoryId, {Database database, int categoryId}) async {
    if (database == null) {
      database = await SqlManager.getCurrentDatabase();
    }

    if (categoryId == null) {
      categoryId = Sqflite.firstIntValue(await database.query(TableMediaCategory.tableName, columns: [TableBase.columnId], where: '${TableMediaCategory.columnOriginId}=?', whereArgs: [originCategoryId]));
    }

    print('将影视[$mediaId]关联到分类[$categoryId]');

    database.insert(TableMediaCategoryMap.tableName, {
      '${TableMediaCategoryMap.columnCategoryId}': categoryId,
      '${TableMediaCategoryMap.columnMediaId}': mediaId,
      '${TableBase.columnCreateTime}': DateTime.now().millisecondsSinceEpoch,
    });
  }

  Future<void> initCategories(List<dynamic> jsonList) async {
    // list操作  https://www.jianshu.com/p/df225c203e96
    // TODO：这个代码不生效，不知道为什么
    // jsonList.map((jsonCategory) => {print('jsonCategory.map')});

    // forEach仍然调用的是for循环。因此我们直接用for循环
    // jsonList.forEach((jsonCategory) {
    //  insert(Category.fromGeneralSpiderJson(jsonCategory));
    // });
    for (Map<String, dynamic> jsonCategory in jsonList) {
      await insert(MediaCategory.fromGeneralSpiderJson(jsonCategory));
    }
    print('当前数据库中存在的分类数量:${(await getCategories()).length}');
  }

  // 获取榜单列表
  Future<List<MediaCategory>> getCategories() async {
    Database db = await SqlManager.getCurrentDatabase();
    List<Map<String, dynamic>> categories = await db.query(tableName);
    // 将数据库查询结果，转换成对象
    List<MediaCategory> categoryList = categories.map((item) => MediaCategory.fromMap(item)).toList();
    print('从[${Config.spiderUrl()}]中查询分类数据完成');
    return categoryList;
  }
}

class TableMediaCategoryMap extends TableBase {
  // 表名
  static final String tableName = 'media_category_map';
  static final String columnCategoryId = "category_id";
  static final String columnMediaId = "media_id";

  @override
  createTable(Database db) {
    db.execute('''create table $tableName (
    ${TableBase.columnId} integer PRIMARY KEY AUTOINCREMENT NOT NULL,
    $columnCategoryId integer,
    $columnMediaId integer,
    ${TableBase.columnCreateTime} integer
    )''');
  }
}
